package com.xiaoyi.springboot.shiro;

import com.alibaba.fastjson.JSON;
import com.xiaoyi.springboot.config.ResponseModel;
import com.xiaoyi.springboot.constant.Constants;
import com.xiaoyi.springboot.enums.ExceptionInfoEnum;
import com.xiaoyi.springboot.enums.UserType;
import com.xiaoyi.springboot.exception.UnauthorizedException;
import com.xiaoyi.springboot.service.SysPermissionService;
import com.xiaoyi.springboot.util.SpringContextUtils;
import com.xiaoyi.springboot.util.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.authc.BasicHttpAuthenticationFilter;
import org.apache.shiro.web.util.WebUtils;
import org.assertj.core.util.Sets;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Objects;
import java.util.Set;

/**
 * @Description: 鉴权登录拦截器
 * @Author: Scott
 * @Date: 2018/10/7
 * 代码的执行流程preHandle->isAccessAllowed->isLoginAttempt->executeLogin
 **/
@Slf4j
public class JwtFilter extends BasicHttpAuthenticationFilter {

	/**
	 * 执行登录认证
	 *
	 * @param request
	 * @param response
	 * @param mappedValue
	 * @return
	 */
	@Override
	protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object mappedValue) {
		return 	executeLogin(request, response);
	}

	/**
	 *
	 */
	@Override
	protected boolean executeLogin(ServletRequest request, ServletResponse response){
		HttpServletRequest httpServletRequest = (HttpServletRequest) request;
		String token = httpServletRequest.getHeader(Constants.X_ACCESS_TOKEN);
		if (StringUtils.isEmpty(token)){
			return false;
		}
		JwtToken jwtToken = JwtUtil.parseJWT(token);
		// 提交给realm进行登入，如果错误他会抛出异常并被捕获
		getSubject(request, response).login(jwtToken);
		// 如果没有抛出异常则代表登入成功，返回true
		return true;
	}
	@Autowired
	SysPermissionService sysPermissionService;
	/**
	 * 对跨域提供支持
	 */
	@Override
	protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception {
		HttpServletRequest httpServletRequest = (HttpServletRequest) request;
		HttpServletResponse httpServletResponse = (HttpServletResponse) response;
		httpServletResponse.setHeader("Access-control-Allow-Origin", httpServletRequest.getHeader("Origin"));
		httpServletResponse.setHeader("Access-Control-Allow-Methods", "GET,POST,OPTIONS,PUT,DELETE");
		httpServletResponse.setHeader("Access-Control-Allow-Headers", httpServletRequest.getHeader("Access-Control-Request-Headers"));
		// 跨域时会首先发送一个option请求，这里我们给option请求直接返回正常状态
		if (httpServletRequest.getMethod().equals(RequestMethod.OPTIONS.name())) {
			httpServletResponse.setStatus(HttpStatus.OK.value());
			return false;
		}

		if(null==sysPermissionService)
			sysPermissionService = SpringContextUtils.getBean(SysPermissionService.class);

		String requestURI = getPathWithinApplication(request);

		// 1、看权限里面有没有维护，如果没有为呼呼，说明接口不需要权限，放行就行了
		// 2、如果维护了，但是该用户没有权限，那么就需要阻断了
		boolean needInterceptor = sysPermissionService.needInterceptor(requestURI);
		if (!needInterceptor) {
			return super.preHandle(request, response);
		} else {

			String token = httpServletRequest.getHeader(Constants.X_ACCESS_TOKEN);
			if (StringUtils.isEmpty(token)){
				return false;
			}
			String username = JwtUtil.getUsername(token);
			String userType = JwtUtil.getUserType(token);
			Set<String> permissionUrls = Sets.newHashSet();
			if (StringUtils.isNotEmpty(userType)){
				boolean hasPermission = false;
				/*if (userType.equals(UserType.ADMINUSER.getValue())){
					permissionUrls = sysPermissionService.listPermissionURLs(username);
				}
				if (userType.equals(UserType.COMMONUSER.getValue())){
					permissionUrls = sysPermissionService.listPermissionURLs(username);
				}*/
				permissionUrls = sysPermissionService.listPermissionURLs(username);
				for (String url : permissionUrls) {
					// 这就表示当前用户有这个权限
					if (url.equals(requestURI)) {
						hasPermission = true;
						break;
					}
				}
				if (hasPermission)
					return super.preHandle(request, response);
				else {
					throw  new UnauthorizedException("当前用户没有访问路径 " + requestURI + " 的权限");
				}
			}
		}
		return super.preHandle(request, response);
	}
}
